package com.ujiuye.util;

import org.apache.commons.io.IOUtils;

import javax.servlet.http.Part;
import java.io.*;
import java.util.UUID;

/**
 * CompanyName: IT优就业<br/>
 * Datetime: 2021/7/2 10:44<br/>
 *
 * @author TanJian
 */
public class UploadFile {

    public static String upload(Part part){

        //1:获取文件名称
        String filename = part.getSubmittedFileName();
        //2:创建虚拟的目录结构
        File file = new File("D:\\A学习文件\\Java二阶段内容\\Java内容\\7月2\\图片");
        if(!file.exists()){
            file.mkdirs();
        }

        //给文件名+随机数
        filename = UUID.randomUUID().toString()+filename;
        InputStream is = null;
        OutputStream os = null;
        try {
            is = part.getInputStream();
            os = new FileOutputStream(file.getPath()+"/"+filename);
            if(part.getSize()>0){
                //上传文件
                IOUtils.copy(is,os);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //返回带UUID的文件名
        return filename;


    }
}

